package com.ruoyi.web.controller.mqtt;


import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.json.JSONObject;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


//// MQTT 缓存服务
public class MqttCacheService {
    // 缓存每个设备的最新传感器数据 key: deviceId -> JSON
    private final Map<String, JSONObject> sensorDataCache = new ConcurrentHashMap<>();



    @PostConstruct
    public void init() {
        // 从数据库加载所有需要监听的设备和 MQTT 配置
        // 启动 MQTT 客户端并订阅
        //startAllMqttClients();
    }

    public JSONObject getLatestData(String deviceId) {
        return sensorDataCache.get(deviceId);
    }
/*
    private void startAllMqttClients() {
        // 伪代码：查询所有需要监听的设备
        List<SnmpSensubjectdevice> devices = snmpSensubjectdeviceService.selectAll();
        for (SnmpSensubjectdevice device : devices) {
            try {
                SnmpSensubjectinfo snmpSensubjectinfo = new SnmpSensubjectinfo();
                snmpSensubjectinfo.setSensorsubject(device.getSensorsubject());
                List<SnmpSensubjectinfo> sensors = snmpSensubjectinfoService.selectSnmpSensubjectinfoList(snmpSensubjectinfo);
                if (sensors == null || sensors.isEmpty()) continue;

                SnmpEquipclient equipClient = snmpEquipclientService.selectSnmpEquipclientById(Long.valueOf(device.getSensorsubject()));
                if (equipClient == null) continue;

                SnmpEquipmentinfo equipment = snmpEquipmentinfoService.selectByEquipmentId(equipClient.getEquipmentid());
                if (equipment == null) continue;

                String broker = "tcp://" + equipment.getEquipmentip() + ":" + equipment.getPort();
                String topic = equipClient.getLoginname() + "/" + equipClient.getPassworld();
                String clientId = equipClient.getClientId();

                connectAndSubscribe(device.getDeviceId(), broker, topic, clientId, sensors);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void connectAndSubscribe(String deviceId, String broker, String topic, String clientId, List<SnmpSensubjectinfo> sensorItems) {
        try {
            MemoryPersistence persistence = new MemoryPersistence();
            MqttClient mqttClient = new MqttClient(broker, clientId, persistence);
            MqttConnectOptions opts = new MqttConnectOptions();
            opts.setCleanSession(true);
            mqttClient.connect(opts);

            mqttClient.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                    System.err.println("MQTT 连接丢失: " + deviceId + " -> " + cause.getMessage());
                }

                @Override
                public void messageArrived(String topic, MqttMessage message) {
                    try {
                        String payload = new String(message.getPayload());
                        JSONObject json = new JSONObject(payload);
                        // 缓存数据
                        sensorDataCache.put(deviceId, json);

                        // 保存历史记录
                        saveSensorHistory(deviceId, json, sensorItems);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {}
            });

            mqttClient.subscribe(topic);
            System.out.println("✅ 已订阅: " + topic + " -> 设备: " + deviceId);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void saveSensorHistory(String deviceId, JSONObject json, List<SnmpSensubjectinfo> sensorItems) {
        List<SnmpSensorinfohistory> historyList = new ArrayList<>();
        for (SnmpSensubjectinfo item : sensorItems) {
            String field = item.getSensorGetdata();
            if (json.has(field)) {
                double value = json.getDouble(field);
                SnmpSensorinfohistory history = new SnmpSensorinfohistory();
                history.setDeviceId(deviceId);
                history.setSensorId(item.getSensorId());
                history.setSensorValue(String.valueOf(value));
                history.setCreateTime(new Date());
                historyList.add(history);
            }
        }
        if (!historyList.isEmpty()) {
            snmpSensorinfohistoryService.insertBatchSnmpSensorinfohistory(historyList);
        }
    }

 */
}
